package cn.huyanbing.middleware.thread.research;

import io.netty.util.concurrent.FastThreadLocal;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

/**
 * @BelongProject middleware
 * @BelongPackage cn.huyanbing.middleware.thread.research
 * @Description  参考：https://zhuanlan.zhihu.com/p/701827052
 * https://blog.csdn.net/mouday/article/details/140414977
 * @ClassName NettyFastThreadLocalTest
 * @Author huyangbing
 * @Date 2024/12/16 19:49
 * @Version 1.0.0
 */
@BenchmarkMode(Mode.Throughput)
@State(value = Scope.Thread)//默认为Scope.Thread,含义是每个线程都会有一个实例
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class NettyFastThreadLocalTest {


    ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "hello FunTester");

    FastThreadLocal<String> fastThreadLocal = new FastThreadLocal<String>() {
        @Override
        protected String initialValue() throws Exception {
            return "hello FunTester";
        }
    };

    @Param({"10", "40", "70", "100"}) // 定义四个参数，之后会分别对这四个参数进行测试
    private int n;


    @Benchmark
    public void threadLocal() {

        for(int i=0;i<n;i++){
            threadLocal.set("threadLocal test"+i);
        }

        threadLocal.get();
    }

    @Benchmark
    public void fastLocal() {

        for(int i=0;i<n;i++){
            fastThreadLocal.set("threadLocal test"+i);
        }
        fastThreadLocal.get();
    }

    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(NettyFastThreadLocalTest.class.getSimpleName())//测试类名
                //.result("long/result.json")//测试结果输出到result.json文件
                .resultFormat(ResultFormatType.JSON)//输出格式
                .forks(1)//fork表示每个测试会fork出几个进程，也就是说每个测试会跑几次
                .threads(40)//测试线程数
                .warmupIterations(2)//预热次数
                .warmupBatchSize(2)//预热批次大小
                .measurementIterations(1)//测试迭代次数
                .measurementBatchSize(1)//测试批次大小
                .build();
        new Runner(options).run();
    }



}
